<?php

namespace app\api\controller;

use app\admin\model\AdminLog;
use app\common\controller\Frontend;
use app\common\library\Upload;
use think\Exception;
use think\exception\FileException;

class Ajax extends Frontend
{
    protected $noNeedLogin = ['*'];

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 上传文件接口
     */
    public function upload()
    {
        AdminLog::setTitle(__('upload'));
        $file = $this->request->file('file');
        try {
            $config = [];
            // 查找远程附件配置
            $storageConfig = get_sys_config("storage_config");
            if ($storageConfig !== 'local') {
                if ($storageConfig === 'oss') {
                    $config['topic'] = 'oss_cos_cloud';
                } else if ($storageConfig === 'cos') {
                    $config['topic'] = 'cos_cloud';
                }
                $config['storage']  = $storageConfig;
                $config['savename'] = "/jueqi_survey_pro/{topic}/{year}{mon}{day}/{filesha1}{.suffix}";
            }
            $upload = new Upload($file, $config);
            $res    = $upload->upload(null, 0, 0);
            if ($res['code'] == 2) {
                $this->error($res['msg']);
            }
            $attachment = $res['data'];
            unset($attachment['create_time'], $attachment['quote']);
        } catch (Exception|FileException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('文件上传成功！'), [
            'file' => $attachment ?? []
        ]);
    }

    public function area()
    {
        $this->success('', get_area());
    }

    public function buildSuffixSvg()
    {
        $suffix     = $this->request->param('suffix', 'file');
        $background = $this->request->param('background');
        $content    = build_suffix_svg((string)$suffix, (string)$background);
        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/svg+xml');
    }
}
